<!DOCTYPE html>
<html>

<head>
  <title><%= title %></title>
  <link rel='stylesheet' href='/stylesheets/style.css' />
</head>

<body>
  <h1><%= title %></h1>
  <textarea name="text" id="text" cols="50" rows="10"><img src="null" onerror="alert(111)"></img></textarea>
  <button id="add">添加</button>
  <button id="get">获取</button>
  <script>
    const addDom = document.getElementById('add')
    const getDom = document.getElementById('get')
    const text = document.getElementById('text')

    function ajaxGet(url) {
      return new Promise((reslove, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url)

        xhr.responseType = 'json' // 返回类型
        // 定义请求完成的处理函数
        xhr.onload = function (e) {
          const res = this.response
          if (this.status === 200) {
            reslove(res)
          } else {
            reject(e)
          }
        }
        xhr.onerror = function (e) {
          reject(e)
        }
        xhr.send()
      })


    }
    addDom.addEventListener('click', function () {
      const textValue = text.value
      console.log('textValue', textValue)
      ajaxGet(`/comment/add?comment=${textValue}`).then(function () {
        console.log('add success')
      })
    })
    getDom.addEventListener('click', function () {
      ajaxGet('/comment/get').then(function (data) {
        console.log(data)
        let divDom = document.createElement('div')
        divDom.innerHTML = data.comment
        document.body.appendChild(divDom)
        divDom = null
        console.log('get success')
      })
    })
  </script>
</body>

</html>